package Z3;

public class MojaLista<T> {
	private class Node {
		T[] array;
		Node next; // dowiazanie do nastepnego rekordu

		Node(T[] a, Node next) {
			this.array = a;
			this.next = next;
		}

		Node() {
			this(null, null);
		}

		boolean end() {
			return array == null && next == null;
		}

		public String toString() {
			String res = "";
			for (int i = 0; i < array.length - 1; i++)
				res += array[i] + ", ";
			res += array[array.length - 1];
			return res;
		}

		T remove(int index) {
			T tmp = array[index];
			array[index] = null;
			return tmp;
		}

		@Override
		public boolean equals(Object o) {
			boolean res = false;
			for (int i = 0; i < array.length; i++) {
				if (array[i] == o)
					res = true;
			}
			return res;
		}
	}

	private Node top = new Node();

	// dodaje kolejne dowiazanie z tablicy
	public void add(T[] arrayToAdd) {
		top = new Node(arrayToAdd, top);
	}

	// zwraca ilosc elementiw zgromadzonych we wszystkich tablicach (nie
	// uwzgladniajac null)
	public int size() {
		Node tmp = top;
		int s = 0;
		while (!tmp.end()) {
			for (int i = 0; i < tmp.array.length; i++) {
				if (tmp.array[i] != null)
					s++;
			}
			tmp = tmp.next;
		}
		return s;
	}

	// czysci cala tablice
	public void clear() {
		top = new Node();
	}

	// zwraca element o danym indeksie
	public T get(int index) {

		Node tmp = top;
		T res = null;
		while (!tmp.end()) {
			for (int i = 0; i < tmp.array.length; i++) {
				if (tmp.array[i] != null)
					index--;
				if (index == -1) {
					res = tmp.array[i];
					break;
				}
			}
			tmp = tmp.next;
		}
		if (res == null)
			throw new ArrayIndexOutOfBoundsException(
					"Podany argument jest wiekszy od ilosci przetrzymywanych elementow!");
		return res;
	}

	// zwraca i usuwa element o podanym indeksie
	public T remove(int index) {
		Node tmp = top;
		boolean conti = true;
		T res = null;
		while (conti) {
			for (int i = 0; i < tmp.array.length; i++) {
				if (tmp.array[i] != null)
					index--;
				if (index == -1) {
					res = tmp.remove(i);
					conti = false;
					break;
				}
			}
			tmp = tmp.next;
		}
		return res;
	}

	public String toString() {
		String res = "";
		Node tmp = top;
		while (!tmp.end()) {
			res += "[" + tmp + "]";
			tmp = tmp.next;
		}
		return res;
	}

	public boolean contain(T t) {
		boolean res = false;
		Node tmp = top;
		while (!tmp.end()) {
			if (tmp.equals(t)) {
				res = true;
			}
			tmp = tmp.next;
		}
		return res;
	}

}
